package webcert.ch03.ex0301;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Properties;

public class ContextInitParms extends HttpServlet {

    @Override
    public void init() throws ServletException {
        String propsFileName = getServletContext().getInitParameter("propsFileName");
        String propsFileLocation = getServletContext().getInitParameter("propsFileLocation");
        String path = getServletContext().getRealPath(propsFileLocation + "/" + propsFileName);

        try {
            FileInputStream fis = new FileInputStream(path);
            Properties properties = new Properties();
            properties.load(fis);
            getServletContext().setAttribute("properties", properties);
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Exception while loading properties");
            e.printStackTrace();

        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Properties properties = (Properties)getServletContext().getAttribute("properties");
        PrintWriter out = response.getWriter();
        out.write("The application name is " + properties.getProperty("application_name"));
        out.write("\n");
        out.write("The application version is " + properties.getProperty("application_version"));


    }
}
